<template>
  <div class="relative w-full h-full page">
    <PageHeader :title="$t('spec_lists.商品规格管理')" />
    <!-- <div class="flex_aic_jcsb">
      <div class="flex_aic">
        <el-input
          v-model="filters.searchKey"
          placeholder="规格名称"
          style="width: 280px"
          class="ml12"
        >
          <template #prefix>
            <span class="color-555555">规格名称</span>
          </template>
        </el-input>
      </div>
      <div class="flex_aic">
        <el-button @click="resetFilters">重置</el-button>
        <el-button type="primary" @click="handleSearch">查询</el-button>
      </div>
    </div> -->
    <div class="mt12 toolbar flex_aic_jcsb" v-my-point="'skuSpecification:add'">
      <div class="addBtn flex_aic_jcc" @click="handleAdd()">
        <SvgIcon name="iconxinzeng" class="mr8" />
        <span>{{ $t('spec_lists.新增规格') }}</span>
      </div>
    </div>
    <el-table
      :data="tableData"
      style="width: 100%; margin-bottom: 20px"
      row-key="id"
      border
      :default-expand-all="false"
      height="calc(100vh - 200px)"
      class="cover-table mt12"
      v-loading="loading"
      lazy
      :load="loadChildSpecs"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      :key="tableKey"
    >
      <el-table-column prop="name" :label="$t('spec_lists.规格名称')">
        <template #default="{ row }">
          {{ row["name" + locale] }}
        </template>
      </el-table-column>
      <el-table-column prop="sort" :label="$t('spec_lists.排序')" />
      <el-table-column prop="address" :label="$t('spec_lists.操作')" width="500px">
        <template #default="scope">
          <div class="flex_aic_jcc">
            <div class="operationBtn">
              <el-button type="text" @click="handleEdit(scope.row)" v-my-point="'skuSpecification:edit'"
                >{{ $t('spec_lists.编辑') }}</el-button
              >
            </div>
            <div class="operationBtn" v-if="!scope.row.specificationId">
              <el-button type="text" @click="handleAddChild(scope.row)" v-my-point="'skuSpecification:add'"
                >{{ $t('spec_lists.新增规格值') }}</el-button
              >
            </div>
            <el-popconfirm
              :title="$t('spec_lists.确定删除吗')"
              @confirm="handleDelete(scope.row)"
              :confirm-button-text="$t('spec_lists.确定')"
              :cancel-button-text="$t('spec_lists.取消')"
              width="260px"
            >
              <template #reference>
                <el-button class="ml0" type="text" size="small" v-my-point="'skuSpecification:del'">{{ $t('spec_lists.删除') }}</el-button>
              </template>
            </el-popconfirm>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- <div class="flex justify-end mt24 absolute bottom-0 right-0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div> -->
    <EditDia
      v-model="editDiaVisible"
      :data="editDiaData"
      @success="handleSuccess"
    ></EditDia>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import EditDia from "./editDia.vue";
import Api from "@/config/api/api";
import { useI18n } from "vue-i18n";

const { locale, t } = useI18n();
const filters = ref({
  searchKey: "",
});

const editDiaVisible = ref(false);
const editDiaData = ref({});
const currentPage = ref(1);
const pageSize = ref(9999);
const total = ref(0);
const tableData = ref([]);
const loading = ref(false);
const tableKey = ref(0);

// 重置过滤条件
const resetFilters = () => {
  filters.value.searchKey = "";
  currentPage.value = 1;
  getDataList();
};

// 查询
const handleSearch = () => {
  currentPage.value = 1;
  getDataList();
};

// 删除规格
const handleDelete = async (row) => {
  try {
    loading.value = true;
    // 根据规格级别选择不同的删除接口
    if (!row.specificationId) {
      await Api.deleteSkuSpecification([row.id]);
    } else {
      await Api.deleteSkuSpecificationDetail([row.id]);
      tableKey.value++;
    }
    ElMessage.success(t('spec_lists.删除成功'));
    getDataList();
  } catch (error) {
    console.error("删除失败", error);
    ElMessage.error(error.message || t('spec_lists.删除失败'));
  } finally {
    loading.value = false;
  }
};

// 编辑规格
const handleEdit = (row) => {
  if(row.specificationId){
    const parentInfo = tableData.value.find(item => item.id === row.specificationId)
    editDiaData.value = JSON.parse(JSON.stringify({
      ...row,
      parentId: row.specificationId,
      parentInfo: {
        ...parentInfo,
      },
    }))
  } else {
    editDiaData.value = JSON.parse(JSON.stringify(row))
  }
  editDiaVisible.value = true;
};

// 新增规格
const handleAdd = () => {
  editDiaVisible.value = true;
  editDiaData.value = {
    name: "",
    sort: 0
  };
};

// 新增子规格
const handleAddChild = (row) => {
  editDiaVisible.value = true;
  editDiaData.value = {
    parentId: row.id,
    parentInfo: {
      ...row,
    },
    name: "",
    sort: 0
  };
};

// 处理分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  getDataList();
};

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page;
  getDataList();
};

// 弹窗操作成功的回调
const handleSuccess = () => {
  tableKey.value++;
  getDataList();
};

// 获取规格列表数据（一级规格）
const getDataList = async () => {
  try {
    loading.value = true;
    const params = {
      page: currentPage.value - 1,
      size: pageSize.value,
    };

    if (filters.value.searchKey) {
      params.name = filters.value.searchKey;
    }

    const res = await Api.skuSpecification_list(params);
    if (res && res.data) {
      // 设置每个一级规格都有子规格（可以懒加载）
      const specData = res.data.content || [];
      specData.forEach((item) => {
        item.hasChildren = true; // 标记为有子节点，触发懒加载
      });

      tableData.value = specData;
      total.value = Number(res.data.totalElements || 0);
    }
  } catch (error) {
    console.error("获取数据失败", error);
    ElMessage.error(error.message || t('spec_lists.获取数据失败'));
  } finally {
    loading.value = false;
  }
};

// 懒加载子规格
const loadChildSpecs = async (row, treeNode, resolve) => {
  try {
    const params = {
      page: 0,
      size: 9999,
      specificationId: row.id, // 添加specificationId参数，值为父规格id
    };

    // 调用子规格查询接口
    const res = await Api.skuSpecificationDetail_list(params);
    if (res && res.data) {
      const childSpecs = (res.data.content || []).map((item) => {
        return {
          ...item,
          hasChildren: false,
          specificationId: row.id, // 为每个子规格添加specificationId
        };
      });
      resolve(childSpecs);
    } else {
      resolve([]);
    }
  } catch (error) {
    console.error("加载子规格失败", error);
    ElMessage.error(error.message || t('spec_lists.加载子规格失败'));
    resolve([]);
  }
};

onMounted(() => {
  getDataList();
});
</script>

<style lang="scss" scoped>
.addBtn {
  height: 28px;
  margin-left: 10px;
  padding: 0 7px;
  border-radius: 3px;
  background: #fff;
  cursor: pointer;
}
.split {
  width: 1px;
  height: 12px;
  background: #ddd;
  margin: 0 5px;
}

.page {
  .cover-table {
    :deep(.el-table__cell) {
      text-align: left;
    }
  }
}
</style>
